//
//  TextViewController.m
//  IOS_socketServer
//
//  Created by Maculish Ting on 15/4/29.
//  Copyright (c) 2015年 LYD. All rights reserved.
//

#import "TextViewController.h"
#import "GCDAsyncUdpSocket.h"

@interface TextViewController ()<GCDAsyncUdpSocketDelegate>
{
    // 状态位——判断是否在运行
    BOOL isRunning;
    // udp访问类
    GCDAsyncUdpSocket *udpSocket;
}

@end

@implementation TextViewController
@synthesize portField;
@synthesize startButton;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark- setup
-(void)setup
{
    // 状态位：0
    isRunning=NO;
    
    self.automaticallyAdjustsScrollViewInsets=NO;
    
    [startButton setTitle:@"start" forState:UIControlStateNormal];
    
    // 点击背景回缩键盘
    [self createGesture];
    
    // Setup our socket.
    // The socket will invoke our delegate methods using the usual delegate paradigm.
    // However, it will invoke the delegate methods on a specified GCD delegate dispatch queue.
    //
    // Now we can configure the delegate dispatch queues however we want.
    // We could simply use the main dispatch queue, so the delegate methods are invoked on the main thread.
    // Or we could use a dedicated dispatch queue, which could be helpful if we were doing a lot of processing.
    //
    // The best approach for your application will depend upon convenience, requirements and performance.
    //
    // For this simple example, we're just going to use the main thread.
    
    // 设置我们的socket
    // socket将使用常用的代理模式调用我们的代理方法
    // 尽管如此，socket会调用的制定的GCD调度队列的方法。
    
    // 现在我们可以按照我们想的来配置代理调度队列
    // 我们可以只调用主调度队列，所以委托方法在主线程中调用
    // 或者我们可以使用一个专门的调度队列，当我们做很多事情的时候这样会很有用
    
    // 根据方便，需求，性能，作出最适合适合你程序的应用。
    
    // 因为这只是一个简单的应用，所以我们在主线程中使用
    
    
    udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
}


- (IBAction)startListen:(id)sender {
    int tmpPort=(int)[portField.text integerValue];
    
    if (isRunning==NO)
    {
        // 开始 socket
        
        BOOL judge=[self portCheck:tmpPort];
        
        int port=[portField.text intValue];
        NSError *error=nil;
        
        if (judge)
        {
            if (![udpSocket bindToPort:port error:&error])
            {
                NSLog(@"连接失败");
                return;
            }
            if (![udpSocket beginReceiving:&error])
            {
                [udpSocket close];
                
                NSLog(@"连接但时候出了问题");
                return;
            }
            
            // 合理性判断成功
            
            [startButton setTitle:@"end" forState:UIControlStateNormal];
            
            NSLog(@"%@",portField.text);
        }

    }
    else
    {
        //  结束socket
        
        [udpSocket close];
        
        [startButton setTitle:@"start" forState:UIControlStateNormal];
        isRunning=NO;
    }

}
//  对端口号进行合理性判断  成功返回 YES,否则 NO
-(BOOL)portCheck:(int)portNum
{
    //  端口范围：范围是从0 到65535（2^16-1）。
    
    if([portField.text isEqual:@""])
    {
        NSLog(@"端口为空");
        return NO;
        
    }else if(portNum<0||portNum>65535)
    {
        NSLog(@"端口越界");
        return NO;
    
    }else
    {
//        // 合理性判断成功
//        
//        [startButton setTitle:@"end" forState:UIControlStateNormal];
//        
//        NSLog(@"%@",portField.text);
        return YES;
    
    }
}

// 协议方法
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
      fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
    if (!isRunning) return;
    
    NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (msg)
    {
        /* If you want to get a display friendly version of the IPv4 or IPv6 address, you could do this:
         
         NSString *host = nil;
         uint16_t port = 0;
         [GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];
         
         */
        
        NSLog(@"%@",msg);
    }
    else
    {
        NSLog(@"有错啊");
    }
    
    [udpSocket sendData:data toAddress:address withTimeout:-1 tag:0];
}

#pragma mark- 2 创建自定义的触摸手势来实现对键盘的隐藏：
-(void)createGesture
{
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到当前view
    [self.view addGestureRecognizer:tapGestureRecognizer];
}

-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [portField resignFirstResponder];
}


@end
